<template>
  <div class="app">
    <!-- <textarea
      name=""
      id=""
      cols="30"
      rows="10"
      v-maxlength="30"
      v-model="ipt"></textarea> -->
    <!-- <input type="text" v-maxlength="10" v-model="ipt" /> -->
    <maxLen type="textarea" maxlength="30" />
  </div>
</template>

<script>
import maxLen from './components/MaxLen' 
export default {
  data() {
    return {
      ipt: "",
    };
  },
  components:{
    maxLen,
  },
  directives: {
    maxlength: {
      inserted(el, binding) {
        let parentWp = el.parentNode; //相当于app
        let iptWp = document.createElement("div");
        let span = document.createElement("span");
        // node.replaceChild (newnode,oldnode ) newnode : 必需，用于替换 oldnode 的对象,oldnode : 必需，被 newnode 替换的对象。
        parentWp.replaceChild(iptWp, el);
        iptWp.appendChild(el);
        iptWp.appendChild(span);
        iptWp.style = "position: relative;display:inline-block;";
        if (el.tagName == "TEXTAREA") {
          span.style =
            " position:absolute;bottom: 5px;right: 5px;font-size:10px;color:#999";
        } else if (el.tagName == "INPUT") {
          span.style =
            " position:absolute;top: 5px;right: 3px;font-size:10px;color:#999";
        }
        span.innerHTML = "0/" + binding.value;
        el.setAttribute("maxlength", binding.value);
      },
      update(el, binding) {
        // console.log(binding.value);//总长度
        let iptLength = el.value.length; //ipt长度
        let span = el.nextElementSibling;
        span.innerHTML = iptLength + "/" + binding.value;
        if (iptLength == binding.value) {
          el.style.color = "coral";
        } else {
          el.style.color = "";
        }
      },
    },
  },
};
</script>

<style scoped>
</style>